//
//  SDTableView.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDTableView.h"
#

#define LoadingMore_Layout_Height 60
#define kGetMoreMinOffset 35

@interface SDTableView () {
    SDEGORefreshTableHeaderView* _refreshHeaderView;
    
    BOOL _gettingMore;
}
@end

@implementation SDTableView

@dynamic delegate;

- (void)setScrollBGView:(UIView*)scrollBGView {
    _scrollBGView = scrollBGView;
    [self insertSubview:_scrollBGView atIndex:0];
}

- (void)didAddSubview:(UIView*)subview {
    [self sendSubviewToBack:_scrollBGView];
}

- (void)setNomoreTipString:(NSString*)tipString {
    QNGetMoreTableViewCellStyle st = _loadingMoreView.style;
    _loadingMoreView.style = QNGetMoreTableViewCellStyleNone;
    _loadingMoreView.nomoreTipString = tipString;
    _loadingMoreView.style = st;
}

- (void)setMoreTipString:(NSString*)tipString {
    QNGetMoreTableViewCellStyle st = _loadingMoreView.style;
    _loadingMoreView.style = QNGetMoreTableViewCellStyleNone;
    _loadingMoreView.moreTipString = tipString;
    _loadingMoreView.style = st;
}

- (void)setRefreshTipString:(NSString*)tipString {
    QNGetMoreTableViewCellStyle st = _loadingMoreView.style;
    _loadingMoreView.style = QNGetMoreTableViewCellStyleNone;
    _loadingMoreView.refreshTipString = tipString;
    _loadingMoreView.style = st;
}

- (void)setTipStringColor:(UIColor*)color {
    _loadingMoreView.customTextLabel.textColor = color;
    _refreshHeaderView.statusLabel.textColor = color;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        _loadingMoreView = [[SDGetMoreView alloc]
                            initWithFrame:CGRectMake(0, -100, self.bounds.size.width, LoadingMore_Layout_Height)];
#ifdef CSLApp
        _loadingMoreView.customTextLabel.textColor = [UIColor grayColor];
#else
    //    _loadingMoreView.customTextLabel.textColor = [UIColor colorWithRGB:0xa2a5a8];
#endif
        
        _loadingMoreView.hasMoreData = YES;
        
        UITapGestureRecognizer* tapGesture =
        [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(getMorePressed)];
        [_loadingMoreView addGestureRecognizer:tapGesture];
        
        [self addRefreshHeaderView];
        [_refreshHeaderView refresh];
        
        self.tableFooterView = _loadingMoreView;
        self.minShowLoadingMoreHeight = frame.size.height;
    }
    return self;
}

- (void)removeRefreshHeaderView {
    [_refreshHeaderView removeFromSuperview];
    _refreshHeaderView = nil;
    self.contentInset = UIEdgeInsetsZero;
}

- (void)addRefreshHeaderView {
    if (nil == _refreshHeaderView) {
        _refreshHeaderView =
        [[SDEGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0,
                                                                      0 - SDEGORefreshTableHeaderViewHeight,
                                                                      self.bounds.size.width,
                                                                      SDEGORefreshTableHeaderViewHeight)];
        _refreshHeaderView.delegate = self;
    }
    
    [self addSubview:_refreshHeaderView];
}

- (void)getMorePressed {
    if (_loadingMoreView.style == QNGetMoreTableViewCellStyleGetMore) {
        _gettingMore = YES;
        [self.delegate tableViewShouldLoadMoreData:self];
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

- (void)setContentSize:(CGSize)contentSize {
    [super setContentSize:contentSize];
    if (!self.useLoadingMoreAsCell && !self.notShowLoadingMore) {
        CGRect frame = _loadingMoreView.frame;
        frame.origin.y = contentSize.height;
        _loadingMoreView.frame = frame;
        
        if (_loadingMoreView.frame.origin.y <
            (self.minShowLoadingMoreHeight < 1.0 ? self.frame.size.height : (MAX(self.minShowLoadingMoreHeight,
                                                                                 self.frame.size.height))) &&
            !self.showLoadingMoreAlways)
            _loadingMoreView.hidden = TRUE;
        else
            _loadingMoreView.hidden = FALSE;
        
        if (_loadingMoreView.superview != self && !_loadingMoreView.hidden)
            [self addSubview:_loadingMoreView];
    }
}

- (void)setNotShowLoadingMore:(BOOL)notShow {
    _notShowLoadingMore = notShow;
    _loadingMoreView.hidden = YES;
}

- (void)setNormalInset:(UIEdgeInsets)normalInset {
    _normalInset = normalInset;
    self.contentInset = normalInset;
    self.scrollIndicatorInsets = normalInset;
}

- (void)scrollViewDidScroll {
    [_refreshHeaderView egoRefreshScrollViewDidScroll:self];
    
    if (_preLoadMore && [SDHttpRequestManagement sharedHttpRequestManagement].currentNetworkStatus != kNotReachable) {
        if (self.contentOffset.y + self.frame.size.height > self.contentSize.height - LoadingMore_Layout_Height &&
            !_gettingMore) {
            BOOL dataRefreshing = [self.delegate tableViewDataIsLoading:self];
            BOOL hasMoreData = [self.delegate tableViewHasMoreData:self];
            
            if (hasMoreData && !dataRefreshing) {
                [_loadingMoreView startLoading];
                _gettingMore = YES;
                [self.delegate tableViewShouldLoadMoreData:self];
            }
        }
    } else {
        if (!_gettingMore && ![self.delegate tableViewDataIsLoading:self]) {
            if (self.contentOffset.y > 0 &&
                self.contentOffset.y + self.bounds.size.height + self.contentInset.top >
                self.contentSize.height + self.contentInset.bottom + kGetMoreMinOffset &&
                self.dragging)
                [_loadingMoreView readyToStartLoading];
            else
                [_loadingMoreView finishLoading];
        }
    }
}

- (void)scrollViewDidEndDragging {
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self];
    
    if (!(_preLoadMore && [SDHttpRequestManagement sharedHttpRequestManagement].currentNetworkStatus != kNotReachable)  && !self.notShowLoadingMore) {
        if (_loadingMoreView.style == QNGetMoreTableViewCellStyleGetMore ||
            _loadingMoreView.style == QNGetMoreTableViewCellStyleFresh) {
            if (self.contentOffset.y > 0 &&
                self.contentOffset.y + self.bounds.size.height + self.contentInset.top >
                self.contentSize.height + self.contentInset.bottom + kGetMoreMinOffset) {
                BOOL dataRefreshing = [self.delegate tableViewDataIsLoading:self];
                if (dataRefreshing == FALSE) {
                    [_loadingMoreView startLoading];
                    _gettingMore = YES;
                    [self.delegate tableViewShouldLoadMoreData:self];
                }
            }
        }
    }
}

- (void)finishedLoading {
    //    [self reloadData];
    
    _loadingMoreView.hasMoreData = [self.delegate tableViewHasMoreData:self];
    [_loadingMoreView finishLoading];
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self];
    
    _gettingMore = NO;
}

- (void)finishedLoadingWithoutReload {
    _loadingMoreView.hasMoreData = [self.delegate tableViewHasMoreData:self];
    [_loadingMoreView finishLoading];
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self];
    
    _gettingMore = NO;
}

- (void)forceLoad {
    [_refreshHeaderView forceLoading:self animate:YES];
}

- (void)simulationRefresh {
    
    //    if ([self.delegate tableViewDataIsLoading:nil])
    //    {
    //        self.isRequestInsert = NO;
    //        [self requestTimeLineWithCache:NO];
    //        _isloading = YES;
    //        return;
    //    }
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.contentOffset = CGPointMake(0, 0);
                     }
                     completion:^(BOOL finished) {
                         self.contentOffset = CGPointMake(0, -70);
                         [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self];
                         
                     }];
}

#pragma mark -
#pragma mark Pull to Loading
- (void)egoRefreshTableHeaderDidTriggerRefresh:(SDEGORefreshTableHeaderView*)view {
    [self.delegate tableViewShouldRefreshData:self];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(SDEGORefreshTableHeaderView*)view {
    return [self.delegate tableViewDataIsLoading:self];
    ;
}

- (NSString*)egoRefreshTableHeaderTitle:(SDEGORefreshTableHeaderView*)view state:(EGOPullRefreshState)aState {
    NSString* text = @"";
    switch (aState) {
        case EGOOPullRefreshPulling:
            text = NSLocalizedString(@"释放更新", @"释放更新");
            break;
        case EGOOPullRefreshNormal:
            text = NSLocalizedString(@"下拉更新", @"下拉更新");
            break;
        case EGOOPullRefreshLoading:
            text = (_refreshLoadingTip ? _refreshLoadingTip : NSLocalizedString(@"正在更新...", @"正在更新.."
                                                                                @"."));
            break;
        default:
            break;
    }
    
    return text;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(SDEGORefreshTableHeaderView*)view {
    return [self.delegate tableViewDataLastUpdateTime:self];
}

@end
